from index.common.tool import DATE_TIME_FMT
from index.dao import user_dao


# 添加信息
from index.protocol.user_protocol import UpdateUserInfo, GetUserInfoResponse


def create_user(username, password, gender):
    user_exists = user_dao.get_user_by_name(username)
    if not user_exists:
        user_id = user_dao.create_user(username, password, gender)
        if user_id:
            msg = "注册成功"
            resp = {
                "code": 0,
                "msg": msg,
                "user_id": user_id,
            }
        else:
            msg = "注册失败"
            resp = {
                "code": -200,
                "msg": msg,
            }

    else:
        resp = {
            "code": -200,
            "msg": "用户名已存在",
        }
    return resp


# 注销
def logoff(user_id):
    msg = user_dao.logoff(user_id)
    if msg:
        resp = {
            "code": 0,
            "msg": "注销成功",
        }
    else:
        resp = {
            "code": -200,
            "msg": "注销失败"
        }
    return resp


# 登录
def login(username, password):
    user = user_dao.login(username, password)
    # user.pop("password")
    # user['create_time'] = user['create_time'].strftime(DATE_TIME_FMT)
    return user


# 添加额外信息
def add_ExtendUserInfo(user_id, signature, nickname):
    exist = user_dao.judge_ExtUserInfo(user_id)
    if not exist:
        res = user_dao.add_ExtendUserInfo(user_id, signature, nickname)
        if res:
            rsp = {
                "code": 0,
                "msg": "添加成功",
                "user_id": user_id,
            }
        else:
            rsp = {
                "code": -200,
                "msg": "添加失败",
            }
    else:
        rsp = {
            "code": -200,
            "msg": "信息已存在，如需修改，请点击修改按钮",
        }
    return rsp


# 获取个人信息
def getUserInfo(user_id):
    userInfo = user_dao.getUserInfo(user_id)
    resp = GetUserInfoResponse(
        user_id=user_id, username=userInfo.username, gender=userInfo.gender,
        register_time=userInfo.create_time.strftime(DATE_TIME_FMT), role=userInfo.role
    )

    if hasattr(userInfo, 'extenduserinfo'):
        resp.signature = userInfo.extenduserinfo.signature or ''
        resp.nickname = userInfo.extenduserinfo.nickname or ''
        resp.avatar = userInfo.extenduserinfo.avatar or ''

    return resp


# 修改个人信息
def update_userInfo(user_id, update_info: UpdateUserInfo):
    user_dao.update_userInfo(user_id, update_info)
